<template>
  <div class="app-container">
    <upload-excel-component :template-url="templateUrl" :on-success="handleSuccess" />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { excelToDate } from '@/utils'
import { uploadEmployee } from '@/api/employees'
export default {
  name: 'Import',
  components: { UploadExcelComponent },
  data() {
    return {

    }
  },
  computed: {
    // 导入类型
    type() {
      return this.$route.query.type
    },
    templateUrl() {
      if (this.$route.query.type === 'employee') {
        return '/excel/员工导入模板.xlsx'
      } else {
        return '/excel/xxx.xlsx'
      }
    }
  },
  methods: {
    // 解析Excel读出的数据, 转成接口所需要的对象字段格式
    resolveExcelData(data) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      // 将中文键名替换成英文
      return data.map(item => {
        const obj = {}
        Object.keys(userRelations).forEach(k => {
          if (k === '入职日期' || k === '转正日期') {
            obj[userRelations[k]] = excelToDate(item[k]) // 处理Excel时间
          } else {
            obj[userRelations[k]] = item[k]
          }
        })
        return obj
      })
    },
    async handleSuccess({ results, header }) {
      if (this.type === 'employee') {
        // console.log(this.resolveExcelData(results))
        const data = this.resolveExcelData(results)
        // 批量导入员工
        await uploadEmployee(data)
      }
      this.$message.success('导入成功')
      this.$router.back()
    }
  }
}
</script>
